package com.airnews.ticket.net;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.airnews.ticket.model.Forecast;
import com.airnews.ticket.model.Passenger;
import com.airnews.ticket.model.Point;
import com.airnews.ticket.model.SeatMap;
import com.airnews.ticket.model.WeatherInfo;
import com.airnews.ticket.util.StringUtil;

public class ParseUtil {
	
	
	public static SeatMap parseSeatMap(JSONObject json) {
		SeatMap seatMap = null;
		try {
			if (json.has("seatMap")) {
				JSONObject seatMapJson = json.optJSONObject("seatMap");
				seatMap = new SeatMap();
				seatMap.rows = seatMapJson.optInt("rows");
				seatMap.columns = seatMapJson.optInt("columns");
				if (seatMapJson.has("points")) {
					JSONArray points = seatMapJson.optJSONArray("points");
					Point point;
					for (int i = 0; i < points.length(); i++) {
						JSONObject pointJson = points.getJSONObject(i);
						point = new Point();
						point.i = pointJson.optInt("i");
						point.j = pointJson.optInt("j");
						point.r = pointJson.optString("r");
						point.c = pointJson.optString("c");
						point.v = pointJson.optString("v");
						seatMap.points.add(point);
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return seatMap;
	}

	public static List<Passenger> parsePassenger(JSONObject json) {
		List<Passenger> passengers = new ArrayList<Passenger>();
		if (json.has("passengers")) {
			JSONArray jsonPassengers = json.optJSONArray("passengers");
			if (jsonPassengers == null) {
				return null;
			}
			Passenger passenger = null;
			for (int i = 0; i < jsonPassengers.length(); i++) {
				JSONObject jsonpassenger = jsonPassengers.optJSONObject(i);
				passenger = new Passenger();
				passenger.setPassengerName(jsonpassenger.optString("name"));
				passenger.setPassengerIDNo(jsonpassenger.optString("seatNo"));
				passenger.setPassagerBirthday(jsonpassenger.optString("ffpNum"));
				passengers.add(passenger);
			}
		}
		return passengers;
	}
public static String parserWeather(String str) {
		if (str == null || "".equals(str))
			return null;
		InputStream inputStream = null;
		try {
			DocumentBuilderFactory dbfactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder db = dbfactory.newDocumentBuilder();
			inputStream = new ByteArrayInputStream(str.getBytes());
			// ����Ŀ��
			Document dom = db.parse(inputStream);
			Element docEle = dom.getDocumentElement();
			if(docEle==null) return null;
			NodeList nl = docEle.getElementsByTagName("current_conditions");
			if (nl != null && nl.getLength() > 0) {
				Element element =  (Element)nl.item(0);
				NodeList node = element.getElementsByTagName("icon");
				if (node != null && node.getLength() > 0) {
					element = (Element) node.item(0);
					return element.getAttribute("data");
				}
//				weatherDto.imageUrl = "http://www.zhmb.gov.cn/picture/00.gif";
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}


	/**
	 * ��������Ԥ����Ϣ
	 * @param str
	 * @return
	 */
	public static WeatherInfo parserWeatherInfo(String str) {
		if (StringUtil.isEmpty(str))
			return null;
		InputStream inputStream = null;
		try {
			DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbfactory.newDocumentBuilder();
			inputStream = new ByteArrayInputStream(str.getBytes());
			// ����Ŀ��
			Document dom = db.parse(inputStream);
			Element docEle = dom.getDocumentElement();
			if(docEle==null) return null;
			
			WeatherInfo weatherInfo = new WeatherInfo();
			Element fiElem = (Element)docEle.getElementsByTagName("forecast_information").item(0);
			weatherInfo.city = getSubElementAttrValue(fiElem, "city", "data");
			weatherInfo.postal_code = getSubElementAttrValue(fiElem, "postal_code", "data");
			weatherInfo.latitude = getSubElementAttrValue(fiElem, "latitude_e6", "data");
			weatherInfo.longitude = getSubElementAttrValue(fiElem, "longitude_e6", "data");
			weatherInfo.forecast_date = getSubElementAttrValue(fiElem, "forecast_date", "data");
			weatherInfo.current_date_time = getSubElementAttrValue(fiElem, "current_date_time", "data");
			weatherInfo.unit_system = getSubElementAttrValue(fiElem, "unit_system", "data");
			
			Element currentForecast= (Element)docEle.getElementsByTagName("current_conditions").item(0);
			Forecast currForecast = new Forecast();
			currForecast.temp_f  = getSubElementAttrValue(currentForecast, "temp_f", "data");
			currForecast.temp_c  = getSubElementAttrValue(currentForecast, "temp_c", "data");
			currForecast.humidity  = getSubElementAttrValue(currentForecast, "humidity", "data");
			currForecast.icon  = getSubElementAttrValue(currentForecast, "icon", "data");
			currForecast.condition  = getSubElementAttrValue(currentForecast, "condition", "data");
			currForecast.wind_condition  = getSubElementAttrValue(currentForecast, "wind_condition", "data");
			weatherInfo.currCondition = currForecast;
			
			NodeList nl = docEle.getElementsByTagName("forecast_conditions");
			for(int i=0,len = nl.getLength(); i < len; i++){
				Element elem = (Element)nl.item(i);
				Forecast forecast = new Forecast();
				forecast.temp_f  = getSubElementAttrValue(elem, "temp_f", "data");
				forecast.temp_c  = getSubElementAttrValue(elem, "temp_c", "data");
				forecast.humidity  = getSubElementAttrValue(elem, "humidity", "data");
				forecast.day_of_week  = getSubElementAttrValue(elem, "day_of_week", "data");
				forecast.low  = getSubElementAttrValue(elem, "low", "data");
				forecast.high  = getSubElementAttrValue(elem, "high", "data");
				forecast.icon  = getSubElementAttrValue(elem, "icon", "data");
				forecast.condition  = getSubElementAttrValue(elem, "condition", "data");
				forecast.wind_condition  = getSubElementAttrValue(elem, "wind_condition", "data");
				weatherInfo.forecastList.add(forecast);
			}
			return weatherInfo;
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/**
	 * ��ȡһ��Ԫ�ؽڵ��ֱ���¼�Ԫ������ֵ
	 * @param parentElement ���ڵ�Ԫ��
	 * @param tagName �ӽڵ��ǩ��
	 * @param attrName ������
	 * @return
	 */
	public static String getSubElementAttrValue(Element parentElement, String tagName, String attrName) {
		NodeList nodeList = parentElement.getElementsByTagName(tagName);
		Element elem = (Element)nodeList.item(0);
		if (elem != null) {
			return elem != null ? elem.getAttribute(attrName) : null;
		}
		return null;
	}
}
